<template>
  <div class="inline-edit">
    <a-input
      v-if="isEdit"
      v-model:value="inlineEditValue"
      @pressEnter="handlePerssEnterOrBlur"
      @blur="handlePerssEnterOrBlur"
      ref="inlineEditRef"
      :maxlength="maxNumber"
    />
    <div class="inline-edit__warper" v-else @click.stop="inlineEditHandle">
      <slot>
        <span>{{ inlineEditValue }}</span>
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import { nextTick, ref, watch } from 'vue'
interface InlineEditProps {
  value: string
  maxNumber?: number
}
const props = withDefaults(defineProps<InlineEditProps>(), {
  maxNumber: 20,
  value: '',
})
const emits = defineEmits(['change'])
const isEdit = ref(false)
const inlineEditValue = ref(props.value)
const cachedInlineEditValue = ref(props.value)
watch(
  () => props.value,
  (val) => {
    cachedInlineEditValue.value = val
    inlineEditValue.value = val
  }
)
const inlineEditRef = ref()
const inlineEditHandle = () => {
  isEdit.value = true
  nextTick(() => {
    inlineEditRef.value.focus()
  })
}
const handlePerssEnterOrBlur = () => {
  isEdit.value = false
  handleEditValue(inlineEditValue.value)
}
const handleEditValue = (val: string) => {
  if (val.length === 0) {
    message.warning('文本不能为空')
    inlineEditValue.value = cachedInlineEditValue.value
  }
  emits('change', val)
}
</script>

<style scoped lang="scss">
.inline-edit {
  width: 100%;
}
</style>
